<?php

/**
 * 
 * @author I. Atanasov <i.atanasov77@gmail.com>
 */
class VS_Doctrine_QueryDebugListener extends Doctrine_EventListener
{
	/**
	 * 
	 * @var array
	 */
    protected static $_queries = array();
    
    /**
     * Destructur
     */
    public function __destruct()
    {
    	$this->_logQueries();
    }
    
    /**
     * 
     * @param Doctrine_Event $event
     */
    public function preStmtExecute(Doctrine_Event $event)
    {   
        $query = $event->getQuery();
        $params = $event->getParams();

        //the below makes some naive assumptions about the queries being logged
        while (sizeof($params) > 0) {
            $param = array_shift($params); 

            if (!is_numeric($param)) {
                $param = sprintf("'%s'", $param);
            }   

            $query = substr_replace($query, $param, strpos($query, '?'), 1); 
        }

        self::$_queries[] = $query;
    }

    /**
     * 
     */
    public static function GetQueries()
    {   
        return self::$_queries;
    }
    
    /**
     * 
     */
    private function _logQueries()
    {
    	$logFile = '/tmp/doctrine_debug';
    	file_put_contents($logFile, '');
    	
    	$count = 0;
    	foreach(self::$_queries as $q){
    		$debugStr = sprintf("[%d] %s\n%s\n\n", ++$count, date("d.m.Y H:i:s"), $q);
			file_put_contents($logFile, $debugStr, FILE_APPEND);
    	}
    }
};
